package org.teremail.smtp.commands;

import java.util.Iterator;
import java.util.List;

import org.teremail.smtp.SMTPCommandFactory;
import org.teremail.smtp.SMTPSession;

/**
 * The extended hello command.
 * 
 * @author Michael Barker
 *
 */
public class EHLOCommand extends SMTPCommand {

    private final static String MSG_HOST = "250%s%s welcomes (%s)";
    private final static String MSG_CAPBILITY = "250%s%s";
    private final static String MSG_501_NODOMAIN = "501 Domain not specified in EHLO";

    public EHLOCommand(List<String> parameters) {
        super("EHLO", parameters);
    }
    
    @Override
    public void process(SMTPSession session) {
        if (getParameters().size() > 0) {
            String clientName = getParameters().get(0);
            String hostName = session.getHostName();
            
            List<String> capabilities = session.getCapabilities();
            
            String delim = capabilities.size() > 0 ? "-" : " ";
            session.write(String.format(MSG_HOST, delim, hostName, clientName));
            
            for (Iterator<String> sIt = capabilities.iterator(); sIt.hasNext();) {
                String capability = sIt.next();
                delim  = sIt.hasNext() ? "-" : " ";
                session.write(String.format(MSG_CAPBILITY, delim, capability));
            }
        } else {
            session.write(MSG_501_NODOMAIN);
        }
    }



    public final static SMTPCommandFactory FACTORY = new SMTPCommandFactory() {

        public SMTPCommand create(List<String> parameters) {
            return new EHLOCommand(parameters);
        }
        
    };

}
